package com.xy_pro.xymanager.controller;

import com.alibaba.fastjson.JSONObject;
import com.xy_pro.xymanager.auth.dto.LoginResponse;
import com.xy_pro.xymanager.auth.dto.ResultResponse;
import com.xy_pro.xymanager.auth.dto.WebChatLogin;
import com.xy_pro.xymanager.helper.MpWeChatUtils;
import com.xy_pro.xymanager.helper.SignUtil;
import com.xy_pro.xymanager.helper.XMLParser;
import com.xy_pro.xymanager.repository.UserRepository;
import com.xy_pro.xymanager.service.AuthService;
import com.xy_pro.xymanager.validator.WXBizDataCrypt;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import jakarta.validation.Valid;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/wechat")
public class WechatController {



    @Autowired
    private AuthService authService;

    private Logger logger = LoggerFactory.getLogger(WechatController.class);

    @Value("${mp_wechat.token}")
    private String token;

    @Autowired
    private MpWeChatUtils mpWeChatUtils;

    // 验证服务器有效性（首次配置URL时调用）
    @GetMapping("/verify")
    public String verifyServer(
            @RequestParam("signature") String signature,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce,
            @RequestParam("echostr") String echostr) {

        if (SignUtil.checkSignature(token, signature, timestamp, nonce)) {
            return echostr;
        }
        return "验证失败";
    }

    // 处理微信推送的消息（POST请求）
    @PostMapping("/verify")
    public String handleMessage(@RequestBody String requestBody) {
        try {
            // 解析XML消息
            Map<String, String> messageMap = XMLParser.parse(requestBody);
            String msgType = messageMap.get("MsgType");

            // 处理关注事件
            if ("event".equals(msgType) && "subscribe".equals(messageMap.get("Event"))) {
                String openId = messageMap.get("FromUserName");
                // 记录用户关注信息到数据库
                logger.info("用户关注: {}", openId);

                // 返回欢迎消息
                return buildTextResponse(openId, "感谢关注！");
            }

            // 其他消息类型处理...
            return "success";
        } catch (Exception e) {
            logger.error("处理微信消息失败", e);
            return "success";
        }
    }

    // 构建文本响应消息
    private String buildTextResponse(String toUser, String content) {
        return String.format(
                "<xml>" +
                        "<ToUserName><![CDATA[%s]]></ToUserName>" +
                        "<FromUserName><![CDATA[公众号ID]]></FromUserName>" +
                        "<CreateTime>%d</CreateTime>" +
                        "<MsgType><![CDATA[text]]></MsgType>" +
                        "<Content><![CDATA[%s]]></Content>" +
                        "</xml>",
                toUser, System.currentTimeMillis() / 1000, content
        );
    }

    /**
     * 手机号绑定接口
     *
     * @return Token + 用户信息
     */
    @PostMapping("/minilogin")
    public ResultResponse<?> login(@Valid @RequestBody WebChatLogin webChatLogin) {
        LoginResponse response = authService.loginWebChat(webChatLogin);
        logger.info("loginResponse: {} " , response);
        return ResultResponse.success(response);
    }

}
